import axios from 'axios'
import store from '@/store'
import router from '@/router'
import qs from 'qs';
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
  timeout: 15000,
  responseType: 'json',
  withCredentials: false,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf?-8'
  }
})

service.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  res => {
    // if(res.data.code===422||res.data.code===424){
    if (res.data.code === 424) {
      store.dispatch('logout2');
      router.replace({
        path: '/login',
        query: { redirect: router.currentRoute.fullPath }
      })
    }
    if (res.config.url == 'order/download') {
      return res
    } else {
      return res.data
    }
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 401:
        case 423:
        case 424:
          // MessageBox('다시등록해주세요', '알림', {
          //   confirmButtonText: '확인'
          // }).then(() => {
          store.dispatch('logout2');
          router.replace({
            path: '/login',
            query: { redirect: router.currentRoute.fullPath }
          })
        // });
      }
    }
  }
)

export default {
  get (url, data) {
    return service({
      method: 'get',
      url: url,
      params: data
    }).then(res => res)
  },
  post (url, data) {
    if (url == "config/uploadImg") {
      let param = new FormData()
      param.append('image', data.image)
      return service({
        headers: { 'Content-Type': 'multipart/form-data' },
        method: 'post',
        url: url,
        data: param
      }).then(res => res)
    } else if (url == "config/uploadFile") {
      let param = new FormData()
      param.append('file', data.file)
      return service({
        headers: { 'Content-Type': 'multipart/form-data' },
        method: 'post',
        url: url,
        data: param
      }).then(res => res)
    } else if (url == "order/download") {
      return service({
        responseType: 'blob',
        method: 'post',
        url: url,
        data: qs.stringify(data),
      }).then(res => res)
    } else {
      return service({
        method: 'post',
        url: url,
        data: qs.stringify(data),
      }).then(res => res)
    }
  }
}
